/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useMemo, useCallback, useEffect, useState } from 'react';
import { connect } from 'dva';
import { Form, Table, DatePicker, Button } from 'antd';
import { debounce } from 'lodash';
import AsyncDownLoad from '@/components/DownloadBar/AsyncDownLoad';
import moment from 'moment';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const initDate = [
  moment()
    .endOf('day')
    .subtract(32, 'days'),
  moment()
    .endOf('day')
    .subtract(1, 'days'),
];
const formate = 'YYYY-MM-DD';

const disabledDate = current =>
  current &&
  current >
    moment()
      .endOf('day')
      .subtract(1, 'days');

const FeeDetail = ({ dispatch, form, loading }) => {
  const { getFieldDecorator, validateFields } = form;

  const [tableData, setTableData] = useState([]);

  const getFormValues = useCallback(
    (cb = () => {}) => {
      validateFields((err, values) => {
        if (err) return;
        const { date = [] } = values;
        const [start, end] = date;
        cb({
          start_time: start.format(formate),
          end_time: end.format(formate),
        });
      });
    },
    [validateFields],
  );

  const getList = useCallback(
    debounce(
      (isExport = 0) => {
        getFormValues(values => {
          dispatch({
            type: 'account/getFeeDetail',
            payload: {
              export: isExport,
              ...values,
            },
          }).then(list => {
            if (!isExport) {
              setTableData(list);
            }
          });
        });
      },
      300,
      {
        leading: true,
        trailing: false,
      },
    ),
    [dispatch, validateFields],
  );

  const getExportAllData = () => {
    let data = {};
    getFormValues(values => {
      data = { ...values, export: 1 };
    });
    return data;
  };

  const columns = useMemo(
    () => [
      {
        title: '账单日期',
        key: 'date',
        dataIndex: 'date',
        align: 'center',
      },
      {
        title: '扣费票量',
        key: 'count',
        dataIndex: 'count',
        align: 'center',
      },
      {
        title: '单价（元）',
        key: 'price',
        dataIndex: 'price',
        align: 'center',
      },
      {
        title: '总金额（元）',
        key: 'total_price',
        dataIndex: 'total_price',
        align: 'center',
      },
      {
        title: '操作',
        key: 'brands',
        dataIndex: 'brands',
        align: 'center',
        render: (brands, { date }) => {
          if (!brands) {
            return '暂无品牌，无法导出';
          }
          return (
            <AsyncDownLoad
              action="/v1/TotalDistribution/GpFinanceDetails/getFinanceDetailsByDate"
              method="POST"
              data={() => ({
                brands,
                date,
                export: 1,
              })}
            >
              <a>导出明细</a>
            </AsyncDownLoad>
          );
        },
      },
    ],
    [],
  );

  useEffect(
    () => {
      getList();
    },
    [getList],
  );

  return (
    <>
      <Form layout="inline" style={{ marginBottom: 24 }}>
        <FormItem label="账单日期">
          {getFieldDecorator('date', {
            initialValue: initDate,
            rules: [
              {
                required: true,
                message: '请选择日期',
              },
            ],
          })(<RangePicker disabledDate={disabledDate} />)}
        </FormItem>
        <FormItem>
          <Button type="primary" icon="search" onClick={() => getList()}>
            查询
          </Button>
        </FormItem>
        <FormItem>
          <AsyncDownLoad
            action="/v1/TotalDistribution/GpFinanceDetails/getFinanceDetailsList"
            method="POST"
            data={getExportAllData}
            disabled={tableData.length === 0}
          >
            <Button type="primary" icon="upload">
              导出
            </Button>
          </AsyncDownLoad>
        </FormItem>
      </Form>
      <Table
        rowKey="date"
        loading={loading}
        columns={columns}
        dataSource={tableData}
        pagination={false}
      />
    </>
  );
};

export default connect(({ loading }) => ({ loading: loading.effects['account/getFeeDetail'] }))(
  React.memo(Form.create()(FeeDetail)),
);
